/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.common.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.util.Assert;

/**
 * 浏览器解析工具
 *
 * @author 挺好的 2023年06月07日 11:03
 */
public final class UserAgentUtils {

    private UserAgentUtils () {
    }

    /**
     * 解析浏览器信息
     *
     * @param request
     *         {@link HttpServletRequest }
     *
     * @return {@link UserAgentUtils.UserAgentInfo}
     */
    public static UserAgentInfo parse (HttpServletRequest request) {
        Assert.notNull(request, " HttpServletRequest must not be null");

        return parse(request.getHeader("User-Agent"));
    }

    /**
     * 解析浏览器信息
     *
     * @param userAgentHeader
     *         User-Agent请求头
     *
     * @return {@link UserAgentUtils.UserAgentInfo}
     */
    public static UserAgentInfo parse (String userAgentHeader) {

        Assert.hasText(userAgentHeader, " user agent header is required");

        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentHeader);

        Browser browser = userAgent.getBrowser();
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();

        // 操作系统
        String os = operatingSystem.getName();
        // 浏览器信息 = 厂商 + 名称
        String browserInfo = browser.getManufacturer() + " " + browser.getName();

        // 浏览器版本
        String browserVersion = userAgent.getBrowserVersion().getVersion();

        // 设备信息
        String deviceType = operatingSystem.getDeviceType().getName();

        return UserAgentInfo.builder().browser(browserInfo).browserVersion(browserVersion).osName(os)
                .deviceType(deviceType).build();

    }

    /**
     * 浏览器解析
     */
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    @EqualsAndHashCode (callSuper = false)
    public static class UserAgentInfo {

        /**
         * 浏览器 = 浏览器的厂商 + 浏览器的名称
         */
        private String browser;

        /**
         * 浏览器版本
         */
        private String browserVersion;

        /**
         * 操作系统名称
         */
        private String osName;

        /**
         * 设备类型
         */
        private String deviceType;
    }
}
